/**
 * Markdown 渲染错误边界组件
 * 防止 Markdown 内容错误导致整个应用崩溃
 */

import React from 'react';
import { AlertTriangle, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';

class MarkdownErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
      errorInfo: null
    };
  }

  static getDerivedStateFromError(error) {
    // 更新状态以显示降级 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 记录错误信息
    console.error('📛 Markdown 渲染错误:', error);
    console.error('错误堆栈:', errorInfo);
    
    this.setState({
      error,
      errorInfo
    });
  }

  handleReset = () => {
    this.setState({
      hasError: false,
      error: null,
      errorInfo: null
    });
  };

  render() {
    if (this.state.hasError) {
      return (
        <Card className="border-red-300 bg-red-50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-red-700">
              <AlertTriangle className="size-5" />
              文档渲染错误
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="text-sm text-gray-700">
              <p className="font-medium mb-2">文档内容可能包含以下问题：</p>
              <ul className="list-disc list-inside space-y-1 ml-2">
                <li>Markdown 语法错误</li>
                <li>未转义的特殊字符（如反引号 <code>`</code>）</li>
                <li>不支持的 HTML 标签</li>
                <li>组件渲染异常</li>
              </ul>
            </div>

            {this.state.error && (
              <details className="bg-white p-4 rounded border border-red-200">
                <summary className="font-medium cursor-pointer text-sm mb-2">
                  查看错误详情
                </summary>
                <div className="text-xs font-mono bg-gray-50 p-3 rounded overflow-x-auto">
                  <div className="text-red-600 mb-2">
                    <strong>错误类型:</strong> {this.state.error.name}
                  </div>
                  <div className="text-red-600 mb-2">
                    <strong>错误信息:</strong> {this.state.error.message}
                  </div>
                  {this.state.errorInfo && (
                    <div className="text-gray-600 mt-2">
                      <strong>错误堆栈:</strong>
                      <pre className="mt-1 whitespace-pre-wrap">
                        {this.state.errorInfo.componentStack}
                      </pre>
                    </div>
                  )}
                </div>
              </details>
            )}

            <div className="flex gap-2">
              <Button
                onClick={this.handleReset}
                variant="outline"
                size="sm"
                className="gap-2"
              >
                <RefreshCw className="size-4" />
                重试
              </Button>
              <Button
                onClick={() => window.location.href = '/documentation'}
                variant="outline"
                size="sm"
              >
                返回文档列表
              </Button>
            </div>

            <div className="text-xs text-gray-500 bg-blue-50 p-3 rounded border border-blue-200">
              <p className="font-medium mb-1">💡 开发者提示：</p>
              <p>如果是 Mock 数据内容错误，请检查 <code>src/lib/api/mock-data/documentation-mock.js</code></p>
              <p className="mt-1">特殊字符需要转义：</p>
              <ul className="list-disc list-inside ml-2 mt-1">
                <li>反引号: <code>`</code> → <code>\`</code></li>
                <li>模板表达式: <code>{'${'}</code> → <code>\${'{'}</code></li>
                <li>反斜杠: <code>\</code> → <code>\\</code></li>
              </ul>
            </div>
          </CardContent>
        </Card>
      );
    }

    return this.props.children;
  }
}

export default MarkdownErrorBoundary;

